package cate.game.role.show;

import cate.game.role.Role;
import cate.game.role.RolePart;
import cate.game.role.show.msg.ActiveDecorationResp;
import cate.game.role.show.msg.ExpiredDecorationResp;
import com.fasterxml.jackson.annotation.JsonIgnore;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import org.springframework.data.annotation.Transient;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@NoteClass( "饰品背包对象")
public abstract class ShowBagTab<E extends ShowItemBase> extends RolePart {

    @NoteField("饰品")
    public List<E> list;

    @Override
    public void initialize(Role role) {
        super.initialize(role);
        if (list == null) {
            list = new ArrayList<>();
        }
        resetCheckTime();
    }

    public abstract byte getType();


    protected abstract E createItem(int tid,long validTime);

    public E getItem(int tid) {
        for (E e : list) {
            if (e.tid == tid) {
                return e;
            }
        }
        return null;
    }

    public final void addItem(E item,int activeItemTid){
        list.add(item);
        resetCheckTime();
        role.sendNow(new ActiveDecorationResp(getType(), item,activeItemTid));
        onAddItem(item);
    }

    public final void addItem(E item){
        addItem(item,0);
    }

    @JsonIgnore
    public boolean isActive(int tid) {
        return getItem(tid) != null;
    }


    @Transient
    @JsonIgnore
    private long checkTime;

    private void resetCheckTime(){
        checkTime = 0;
        for (E item : list) {
            if (item.expireTime > 0 && (checkTime == 0 || checkTime > item.expireTime)) {
                checkTime = item.expireTime;
            }
        }
    }

    public void tick() {
        if (checkTime <= 0 || checkTime > System.currentTimeMillis()) {
            return;
        }
        List<Integer> expireTids = new ArrayList<>();
        Iterator<E> it = list.iterator();
        while (it.hasNext()) {
            E e = it.next();
            if (e.expired()) {
                expireTids.add(e.tid);
                it.remove();
            }
        }
        if (!expireTids.isEmpty()) {
            onInvalid(expireTids);
            role.sendNow(new ExpiredDecorationResp(getType(), expireTids));
            resetCheckTime();
        }
    }

    /** 添加饰品时 */
    public void onAddItem(E item){

    }

    /** 饰品过期时 */
    public abstract void onInvalid(List<Integer> expireTids);

}
